const userServ = require('../services/userService')
const { asyncHandler } = require('../routes/getSendResult')
const jwt = require('../routes/jwt')

// 注册
exports.register = asyncHandler(async (req) => {
  return await userServ.register(req.body)
})

// 登录
exports.login = asyncHandler(async (req, res) => {
  const result = await userServ.login(req.body.username, req.body.password)
  if (result) {
    let value = result.id
    //登录成功
    jwt.publish(res, undefined, { id: value })
  }
  // 用户不存在
  return result
})

// 获取所有用户
exports.allUser = asyncHandler(async (req) => {
  return await userServ.getAllUser()
})

// 获取当前用户
exports.getCurrentUser = asyncHandler(async (req) => {
  return await userServ.getCurrentUser(req.body.username)
})

// 修改密码
exports.updateCurrentUser = asyncHandler(async (req) => {
  const user = {
    username: req.body.username,
    password: req.body.password
  }
  return await userServ.updateUser(req.params.userId, user)
})

// 删除用户
exports.deleteUser = asyncHandler(async (req) => {
  return await userServ.deleteUser(req.params.userId)
})
